package org.dandsoft.blackbox.snn;

import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: dvilyuzhanin
 * Date: 24.03.2009 18:30:10
 */
public class EnviromentTraceWriter {
    public final static int FILE_MAGIC = 0x24081986;


    private int min;
    private int max;
    private File file;
    private ObjectId[] ids;
    private Value[] values;
    private DataOutputStream out;

    public EnviromentTraceWriter(int min, int max, File file) throws IOException {
        this.min = min;
        this.max = max;
        this.file = file;
        boolean isFileExist = file.exists();
        out = new DataOutputStream(new FileOutputStream(file, false));

        out.writeInt(min);
        out.writeInt(max);
        ids = new ObjectId[max - min + 1];
        values = new Value[max - min + 1];
    }


    public void put(ObjectId id, Value value) {
        if (id.getValue() >= min && id.getValue() <= max) {
            ids[id.getValue() - min] = id;
            values[id.getValue() - min] = value;
        }
    }

    public void flush(long time) {
        try {
            for (int i = 0; i < ids.length; i++) {
                if (ids[i] != null) {
                    out.writeInt(ids[i].getValue());
                } else {
                    out.writeInt(Integer.MIN_VALUE);
                }
                if (values[i] != null) {
                    out.writeFloat(values[i].getValue());
                } else {
                    out.writeFloat(Float.MAX_VALUE);
                }

                ids[i] = null;
                values[i] = null;
            }
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void close() {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
